package com.cxhome.cxinfox.provider;

import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.traffic.managent.base.BaseService;
import com.traffic.managent.base.Paginator;
import com.traffic.managent.model.product.Provider;
import com.traffic.managent.util.SQLUtils;
import com.traffic.managent.util.UtilsUtils;

/**
 * 供应商业务处理类
 * 
 */
public class ProviderService extends BaseService {

	private final static Logger log = Logger.getLogger(ProviderService.class);
	public static final ProviderService service = new ProviderService();

	public Page<Provider> paginate(Provider model, Paginator paginate, StringBuilder orderSql) {
		SQLUtils sql = new SQLUtils(" from cx_provider pi where 1 = 1  ");

		if (model.getAttrValues().length != 0) {
			sql.setAlias("pi");
			sql.whereLike("ids", model.getStr("ids"));
			sql.whereEquals("delFlag", model.getStr("delFlag"));
			sql.whereEquals("channel", model.getStr("channel"));
		}
		sql.append(orderSql);
		return Provider.dao.paginate(paginate, "select pi.*  ", sql.toString());

	}

	public void delete(String ids, String username, String delFlag) {
		delFlag = "0".equals(delFlag) ? "1" : "0";
		// 逻辑删除
		Db.update("update cx_provider set modifyTime = now(), delFlag = ?,modifyBy= ? where 1=1 and ids = ?", delFlag,
				username, ids);
		// 删除缓存
		Provider.dao.cacheRemove(ids);

	}

	public void saveOrUpdate(String pid, Provider model, String userid) {

		// 数据更新
		Date now = new Date();
		if (pid != null && !"".equals(pid)) { // 更新
			model.put("modifyBy", userid);
			model.put("modifyTime", now);
			model.update();
		} else { // 新增
			model.put("createBy", userid);
			model.put("createTime", now);
			model.put("ids", UtilsUtils.getRandomId(30));
			model.save();
		}
		// 缓存更新
		Provider.dao.cacheAdd(model);

	}

	/**
	 * 供应商复选框
	 * 
	 * @return
	 */
	public String selectProvider(String selected) {

		List<Provider> list = Provider.dao.find(" select ids,providerName from cx_provider order by createTime desc ");

		StringBuffer sb = new StringBuffer("");

		if (list != null && list.size() > 0) {
			for (Provider provider : list) {
				sb.append("<option value=\"");
				sb.append(provider.getStr("ids"));
				sb.append("\" ");
				sb.append((selected != null && provider.getStr("ids").equals(selected)) ? "selected" : "");
				sb.append(">");
				sb.append(provider.getStr("providerName"));
				sb.append("</option>");
			}
		}
		return sb.toString();
	}
}
